package com.snow.demo.app.security;

import org.apache.commons.codec.binary.StringUtils;
import org.bouncycastle.util.encoders.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

public class TestAbv {

    /**
     * 加密
     * @param content 待加密内容
     * @param password  加密密钥
     * @return
     */
    public static byte[] encrypt(String content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(byteContent);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**解密
     * @param content  待解密内容
     * @param password 解密密钥
     * @return
     */
    public static byte[] decrypt(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(content);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //0-正常使用
    public static void main(String[] args) throws Exception{
        String content = "特殊汉字测试特殊aaa汉字测试特殊汉字测试特殊汉字测试1aaaa";
        String password = "12345678";
        //加密
        System.out.println("加密前1：" + content);
        byte[] encryptResult = encrypt(content, password);  // 普通加密
//        String strEncryptResult = ByteUtils.encodeHexString(encryptResult);
        String strEncryptResult = StringUtils.newStringUtf8(Base64.encode(encryptResult));
                System.out.println("加密后1：" + strEncryptResult);
        //解密
//        byte[] byteDecryptResult = ByteUtils.hexStringToBytes(strEncryptResult);

        byte[] byteDecryptResult = Base64.decode(strEncryptResult);

        byte[] decryptResult = decrypt(byteDecryptResult, password);    // 普通解密
        System.out.println("解密后1：" + new String(decryptResult));
    }



}
